package com.shop.admin.aspect;

import com.shop.admin.Interceptor.GetAdminsInfoInterceptor;
import com.shop.admin.aspect.interce.PowerCheckInterce;
import com.shop.admin.model.po.Admins;
import com.shop.ex.ShoppingException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 'banxia'
 * @version 1.0
 * @description 校验方法中是否存在@PowerCheckInterce注解
 * @date 2023/2/26 21:18
 */
@Aspect
@Component
public class AdminPowerCheckoutAspect {

    //com.shop.admin.api下的所有类都会被扫描到。
    @Pointcut("execution(public * com.shop.admin.api.*.*(..))")
    public void powerCheck(){}

    //----------------------------------------------------------------
    //这里暂时没有提供对类注解的扫描...这样有助于权限的细化
    //----------------------------------------------------------------
    @Before("powerCheck()")
    public void doBefore(JoinPoint joinPoint){
        PowerCheckInterce annotation = null;
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        Signature signature = joinPoint.getSignature();
        //获取方法上的注解
        annotation = method.getAnnotation(PowerCheckInterce.class);
        if (annotation != null) {
            String s = annotation.needPower();
            System.out.println("访问该功能所需要的权限为:"+s);
            Admins admins = GetAdminsInfoInterceptor.getAdmins();
            if (admins==null){
                ShoppingException.ThrowShoppingException("该功能需要先登录后有权限才可以访问");
            }
            if (admins.getPower().indexOf(s)==-1){
                ShoppingException.ThrowShoppingException("权限不够,当前用户的权限为:"+admins.getPower());
            }
        }
    }
}
